# encoding: utf-8
'''
Created on 2014-12-29
@chapter: 4.2.2
@name: 拉格朗日插值
@author: revol
'''
from algorithms.solve import Solve
import math

class LagrangeInt(Solve):
    '''
    '''
    def __init__(self,data=[]):
        Solve.__init__(self, data)
        self._name=u'拉格朗日插值'
        self._description=u'拉格朗日插值'
        self._paramenters=[{'name':'points','type':self.typeLIST},
                           {'name':'x','type':self.typeFLOAT}]

    def f(self,x):
        return self.lagint(self._data['points'], x)
    
    def calc(self,data):
        Solve.calc(self, data)
        p=data['points']
        x=data['x']
        self._result=self.lagint(p, x)
        return self._result
    
    def lagint(self,p,x):
        n=len(p)
        y = 0
        for i in xrange(n):
            t = 1
            for j in xrange(n):
                if i!=j:
                    t = t*(x-p[j][0])/(p[i][0]-p[j][0])
            y = y+t*p[i][1]
        return y
        
    
    def getOutput(self):
        Solve.getOutput(self)
        ptable='x | '
        xt=[]
        yt=[]
        for p in self._data['points']:
            xt.append(p[0])
            yt.append(p[1])
        for i in xt:
            ptable=ptable+'%0.4f\t| '%i
        ptable+='\ny | '
        for i in yt:
            ptable=ptable+'%0.4f\t| '%i
        ptable+='\n'
        out=u'''参数：
    坐标表：
%s
    x：%f
        
结果：
    %f'''%(ptable,self._data['x'],self._result)
        return out 
        
        
if __name__ == '__main__':
    data={'points':[(100.0,10.0),(121.0,11.0),(144.0,12.0)],'x':115.0}
    test=LagrangeInt(data)
    print test.getOutput()
    print test.getResult()
    print 'sqrt(5.0）=%f'%math.sqrt(115.0)
    print test.getDescription()
    print test.getParamenters()